<template>
  <el-container class="course-container">
    <!-- 搜索区域 -->
    <el-header class="search-header">
      <el-row :gutter="20" justify="space-between" align="middle">
        <el-col :span="8">
          <el-input
              v-model="searchForm.courseName"
              placeholder="请输入课程名称"
              clearable
              prefix-icon="el-icon-search"
          >
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-input
              v-model="searchForm.userId"
              placeholder="请输入用户名"
              clearable
              prefix-icon="el-icon-user-solid"
          >
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button
              type="primary"
              icon="Search"
              @click="handleSearch"
              :loading="loading"
          >
            搜索
          </el-button>
        </el-col>
      </el-row>
    </el-header>

    <!-- 课程表格 -->
    <el-main class="main-content">
      <el-table
          :data="courses"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载评价数据中..."
          :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="courseName" label="课程名称" width="200" />
        <el-table-column prop="userId" label="用户ID" width="150" />
        <el-table-column prop="reviewContent" label="评价内容" width="300">
          <template #default="{ row }">
            <el-tooltip :content="row.reviewContent" placement="top">
              <span class="ellipsis-text">{{ row.reviewContent }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="评价时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.reviewTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled show-score text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="handleDetail(scope.row)"
                icon="View"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-main>

    <!-- 详情弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        title="评价详情"
        :width="isMobile ? '95%' : '70%'"
        class="detail-dialog"
        :before-close="handleClose"
    >
      <el-form :model="form" label-width="120px" class="detail-form">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="课程名称">
              <el-input v-model="form.courseName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户ID">
              <el-input v-model="form.userId" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="评价内容">
              <el-input
                  v-model="form.reviewContent"
                  type="textarea"
                  :rows="4"
                  disabled
                  class="detail-textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评分">
              <el-rate v-model="form.rating" disabled show-score text-color="#ff9900" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价时间">
              <el-input v-model="form.reviewTime" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import courseHttp from '@/http/http.js';

// 响应式数据
const courses = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isMobile = ref(window.innerWidth < 768);

// 分页配置
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  courseName: '',
  consultantId: ''
});

// 表单数据
const form = reactive({
  courseName: '',
  consultantId: '',
  videoFileName: '',
  createTime: '',
  studyCount: 0
});

// API配置
const api = {
  fetchCourses: (params) => courseHttp.get('/zh/courseReview/page', { params }),
  searchCourses: (params) => courseHttp.get('/zh/courseReview/search', { params })
};

const fetchCourses = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    const res = await api.fetchCourses(params);
    if (res.code === 200) {
      courses.value = res.data.list.map(item => ({
        ...item,
        createTime: dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')
      }));
      total.value = res.data.total;
    }
  } catch (error) {
    handleError(error);
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  try {
    loading.value = true;
    currentPage.value = 1;
    pageSize.value = 10;

    const params = {
      courseName: searchForm.courseName?.trim() ?? '',
      consultantId: searchForm.consultantId?.toString?.() ?? '',
      pageNum: 1,
      pageSize: pageSize.value
    };
    if (!params.courseName && !params.consultantId) {
      ElMessage.warning('请至少输入一个搜索条件');
      return;
    }
    const res = await api.searchCourses(params);

    if (!res.data || res.code !== 200) {
      throw new Error(res.message || '搜索失败');
    }

    courses.value = res.data.list|| [];
    total.value = Number(res.data.total) || 0;


  } catch (error) {
    handleError(error);
    courses.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchCourses();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchCourses();
};

const handleDetail = (row) => {
  Object.assign(form, row);
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const resetForm = () => {
  Object.keys(form).forEach(key => form[key] = '');
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const handleError = (error) => {
  console.error('API Error:', error);
  ElMessage.error(error.message || '操作失败');
};

onMounted(() => {
  window.addEventListener('resize', () => {
    isMobile.value = window.innerWidth < 768;
  });
  fetchCourses();
});
</script>

<style scoped>
.course-container {
  padding: 20px;
  background: #f8f9fa;
  min-height: 100vh;
}

.search-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
}

.main-content {
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 20px 0;
}

/* 表格优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}
.el-table th {
  background-color: #f8f9fa !important;
}

/* 弹窗样式 */
.detail-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.detail-form {
  padding: 24px;
}

.detail-textarea {
  background-color: #f9f9f9;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

/* 文本溢出处理 */
.ellipsis-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-pagination {
    display: flex-wrap;
  }

  .el-col-8 {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>